<script setup lang="ts">
import {memberLabelOpts, statusOpts, yesOrNoOpts} from "@/utils/status";
import {memberFields, memberIntegralFields} from "@/utils/field";
import {deleteMember, getMemberForm, getMemberList, updateIntegral, updateMember,} from "@/api/member";
import {MemberForm, MemberQuery} from "@/api/member/types";
import {getParkOptions} from "@/api/shop/park";
import {phoneReplace} from "@/utils";

defineOptions({
  name: "Member",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);
const lastPage = ref(0);

const modelFields = memberFields();
const modelIntegralFields = memberIntegralFields();
const statusOptions = statusOpts();
const yesOrNoOptions = yesOrNoOpts();
const memberLabelOpttions = memberLabelOpts();
const current_role = localStorage.getItem("role_name");

const queryParams = reactive<MemberQuery>({
  pageNum: 1,
  pageSize: 10,
});
const lists = ref<MemberQuery[]>();

const dialog = reactive({
  title: "",
  visible: false,
  visibleIntegral: false,
});

const formData = reactive<MemberForm>({
  status: 1,
});

const formIntegralData = reactive<MemberForm>({
  integralType: 1,
});

const rules = reactive({
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
  type: [{required: true, message: "请选择标签", trigger: "blur"}],
});

const integralRules = reactive({
  integralType: [{required: true, message: "修改类型", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getMemberList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;

      lists.value?.forEach((data: any) => {
        if (current_role !== 'sys') {
          data.mobile = phoneReplace(data.mobile || 0);
        }
      })

      total.value = data.total;
      lastPage.value = data.lastPage || 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 打开积分框
 * @param row
 */
function openIntegralDialog(row: any) {
  dialog.visibleIntegral = true;
  dialog.title = "积分管理";

  Object.assign(formIntegralData, {id: row.id});
}

/** 打开表单弹窗 */
function openDialog(id?: number) {
  dialog.visible = true;

  if (id) {
    dialog.title = "修改会员";
    getMemberForm(id).then(({data}) => {
      formData.is_deliver = 0;
      formData.is_replace_order = 0;
      Object.assign(formData, data);
    });
  }
}

/** 保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;

      if (formData.id) {
        updateMember(formData.id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ElMessage.success("修改失败");
      }
    }
  });
}

/** 保存提交 */
function handleIntegralSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;

      if (formIntegralData.id) {
        updateIntegral(formIntegralData.id, formIntegralData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ElMessage.success("修改失败");
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog() {
  if (dialog.visible) {
    resetForm();
  }
  dialog.visible = false;
  dialog.visibleIntegral = false;
}

/** 重置表单 */
function resetForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("参数错误");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteMember(id)
      .then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(() => {
  handleQuery();

  getParkOptions().then(res => {
    modelFields['park_id'].options = res.data || []
  })

});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form
        class="pull-left"
        ref="queryFormRef"
        :model="queryParams"
        :inline="true"
      >
        <el-form-item prop="keywords" label="">
          <el-input
            v-model="queryParams.uid"
            placeholder="会员编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="mobile" label="">
          <el-input
            v-model="queryParams.mobile"
            placeholder="手机号码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="username" label="">
          <el-input v-model="queryParams.username" placeholder="会员昵称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table ref="dataTableRef" v-loading="loading" :data="lists" highlight-current-row>
        <el-table-column label="用户编号" prop="id" min-width="100"/>
        <el-table-column label="用户昵称" prop="username"/>
        <el-table-column label="所管园区" prop="avatar">
          <template #default="scope">
            <!--            <el-avatar
                          shape="square"
                          :size="60"
                          :src="scope.row.avatar"
                          v-if="scope.row.avatar"
                        />-->
            <el-tag type="primary" class="margin5-b" v-for="park in scope.row.parks">{{ park }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="手机号码" prop="mobile"/>
        <el-table-column label="积分" prop="integral"/>
        <el-table-column label="类型" prop="is_replace_order">
          <template #default="scope">
            <span v-if="scope.row.is_deliver == 1">配送员</span>
            <span v-else>会员</span>
            <div>
              <el-button v-if="scope.row.is_replace_order == 1" size="small" type="warning">代</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标签" prop="type">
          <template #default="scope">
            <el-tag :type="type%2== 1 ? 'danger':'success'" v-for="(type,tidx) in scope.row.types" class="margin5-r">
              {{ memberLabelOpttions[type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="注册时间" prop="reg_time"/>
        <el-table-column label="来源" prop="subscribe_scene_title"/>
        <el-table-column fixed="right" label="操作" width="160" v-if="current_role == 'sys'">
          <template #default="scope">
            <el-button v-hasPerm="['member:update_integral']" type="primary" size="small" link
                       @click="openIntegralDialog(scope.row)">
              <i-ep-edit class="margin3-r"/>
              积分管理
            </el-button>
            <el-button v-hasPerm="['member:edit']" type="primary" size="small" link @click="openDialog(scope.row.id)">
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>

            <el-button v-hasPerm="['member:delete']" type="danger" size="small" link
                       @click="handleDelete(scope.row.id)">
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:lastPage="lastPage" v-model:page="queryParams.pageNum"
                  v-model:limit="queryParams.pageSize" @pagination="handleQuery"/>
    </el-card>

    <!-- 增加/减少积分 -->
    <el-dialog
      v-model="dialog.visibleIntegral"
      :title="dialog.title"
      width="540px"
      @close="closeDialog"
    >
      <el-form
        ref="objFormRef"
        :model="formIntegralData"
        :rules="integralRules"
        label-width="140px"
      >
        <el-form-item
          :label="field.title"
          :prop="fk.toString()"
          v-for="(field, fk) in modelIntegralFields"
          :key="fk"
        >
          <el-radio-group v-model="formIntegralData[fk]" v-if="field.type == 'radio'">
            <el-radio :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
          </el-radio-group>
          <el-select
            v-model="formIntegralData[fk]"
            v-else-if="field.type == 'select'"
          >
            <el-option
              :key="Number(op.id)"
              :label="op.title"
              v-for="op in field.options"
              :value="Number(op.id)"
            />
          </el-select>
          <el-input
            :type="field.type || 'text'"
            :disabled="field.disabled"
            v-model="formIntegralData[fk]"
            :placeholder="'请输入' + field.title"
            v-else
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleIntegralSubmit">确 定</el-button>
          <el-button @click="closeDialog" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="640px" @close="closeDialog">
      <el-form ref="objFormRef" :model="formData" :rules="rules" label-width="140px">

        <template v-for="(field, fk) in modelFields">

          <el-form-item :label="field.title" :prop="fk.toString()" :key="fk"
                        v-if="!field.relateKey || (field.relateKey  && formData[field.relateKey] == field.relateVal)">
            <el-radio-group v-model="formData[fk]" v-if="field.type == 'radio'">
              <el-radio :label="Number(ok)" v-for="(op, ok) in field.options" :key="ok">{{ op }}</el-radio>
            </el-radio-group>

            <el-checkbox-group v-model="formData[fk]" v-else-if="field.type == 'checkbox'">
              <el-checkbox :label="Number(field.range_key ? op.id : ok)" v-for="(op, ok) in field.options" :key="ok">
                {{ op[field.range_key] || op }}
              </el-checkbox>
            </el-checkbox-group>

            <el-select v-model="formData[fk]" v-else-if="field.type == 'select'">
              <el-option :key="Number(op.id)" :label="op.title" v-for="op in field.options" :value="Number(op.id)"/>
            </el-select>

            <el-input :type="field.type || 'text'" v-model="formData[fk]" :placeholder="'请输入' + field.title" v-else/>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog" type="default">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
